package com.example.controller;

import com.example.pojo.ResultBean;
import com.example.pojo.SysUser;
import com.example.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    ISysUserService userService;

    /**
     * 用户登录
     * @param username
     * @param password
     * @param code
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public ResultBean login(String username,String password,String code,HttpSession session){
        //判断验证码是否正确
        String okCode = (String) session.getAttribute("code");
        if (!okCode.toLowerCase().equals(code.toLowerCase().trim())){
            return ResultBean.error("验证码错误");
        }
        //获取验证主体对象
        Subject subject = SecurityUtils.getSubject();
        //构建登录对象
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //登录
        subject.login(token);

        //判断是否登录成功
        if (subject.isAuthenticated()){
            //获取登录主体并返回前端
            SysUser user = (SysUser) subject.getPrincipal();
            return ResultBean.success(user);
        }else {
            return ResultBean.error("账号或密码错误");
        }
    }

    /**
     * 修改密码
     * @param map
     * @return
     */
    @PostMapping("/updatePassword")
    private ResultBean updatePassword(@RequestBody Map<String,Object> map){
        map.forEach((k,v) -> System.out.println(k + ":" + v));
        SysUser user = userService.getById(map.get("id").toString());
        Md5Hash old = new Md5Hash(map.get("oldPassword"),user.getUsername(),3);
        if (old.toString().equals(user.getPassword())){
            Md5Hash newPassword = new Md5Hash(map.get("newPassword"),user.getUsername(),3);
            user.setPassword(newPassword.toString());
            boolean rs = userService.updateById(user);
            return rs ? ResultBean.success() : ResultBean.error();
        }else {
            return ResultBean.error("原始密码不正确，修改失败");
        }
    }

    /**
     * 测试权限
     * @return
     */
    @GetMapping("testPermission")
    @RequiresPermissions(value = {"center:select","aa"})
    public ResultBean testPermission(){
        return ResultBean.success();
    }
}
